package com.alphas.xixibackendalphas.common;

import lombok.Data;

import java.io.Serializable;

/**
 * 通用返回对象，使用双检锁单例模式保证多线程安全
 * @param <T>
 */
@Data
public class BaseResponse<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 数据
     */
    private T data;
    /**
     * 状态码
     */
    private Integer code;
    private String message;
    private String description;

//    /**
//     * 双重检查锁模式
//     */

//    private volatile static BaseResponse instance;

    /**
     * 私有构造函数，防止被外部调用
     */
    private BaseResponse(){}

    public BaseResponse(StatusCode statusCode) {
        this.code = statusCode.getCode();
        this.message = statusCode.getMessage();
        this.description = statusCode.getDescription();
    }

    public BaseResponse(T data, StatusCode statusCode) {
        this.data = data;
        this.code = statusCode.getCode();
        this.message = statusCode.getMessage();
        this.description = statusCode.getDescription();
    }

    /**
     *
     * @param data  数据
     * @return  通用响应对象
     * @param <T>   返回传入类型
     */
    public static <T> BaseResponse<T> success(T data) {
//        if (instance == null){
//            synchronized (BaseResponse.class){
//                if (instance == null){
//                    instance = new BaseResponse(data,StatusCode.SUCCESS);
//                }
//            }
//        }
//        return instance;
        return new BaseResponse(data, StatusCode.SUCCESS);
    }
    public static <T> BaseResponse<T> success() {
//        if (instance == null){
//            synchronized (BaseResponse.class){
//                if (instance == null){
//                    instance = new BaseResponse(StatusCode.SUCCESS);
//                }
//            }
//        }
//        return instance;
        return new BaseResponse(StatusCode.SUCCESS);
    }

    /**
     *
     * @param statusCode 状态码
     * @return  通用响应对象
     * @param <T>   返回传入类型
     */
    public static <T> BaseResponse<T> error(StatusCode statusCode) {
//        if (instance == null){
//            synchronized (BaseResponse.class){
//                if (instance == null){
//                    instance = new BaseResponse(null,statusCode);
//                }
//            }
//        }
//        return instance;
        return new BaseResponse(null, statusCode);
    }
}
